package com.rfid.acs;


import com.rfid.acs.net.tcp.FiledId;

import java.lang.reflect.Field;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 文件名:AcsResponseBean
 * 创建者:mengqi.wang
 * 创建日期:2018\11\14 0014 14:13
 * 描述: TODO
 */
abstract class AcsResponseBean {

    /**
     * 响应字符串的头部
     */
    private String header;

    /**
     * 指令发送时间
     */
    private String date;

    /**
     * 验证码
     */
    private String sequenceNumber;

    public AcsResponseBean(String source) {
        if (source == null) {
            throw new RuntimeException("source 不能为空");
        }

        parseSource(source);
    }

    private void parseSource(String source) {

        //去掉头部
        int headerLength = 0;

        for (int i = 0; i < source.length(); i++) {
            char c = source.charAt(i);
            if (c == ' ' || (c >= '0' && c <= '9') || c == 'Y' || c == 'N') {
                headerLength += 1;
            } else {
                break;
            }
        }

        header = source.substring(0, headerLength);
        source = source.substring(headerLength, source.length());

        if (source != null && source.contains("|")) {
            String[] split = source.split("\\|");
            Map<String, String> temp = new LinkedHashMap<String, String>();

            for (String str : split) {
                if (str.length() > 2) {//大于2说明有值
                    String key = str.substring(0, 2);
                    String value = str.substring(2, str.length());
                    temp.put(key, value);
                }
            }

            Class<? extends AcsResponseBean> clazz = this.getClass();
            Field[] fields = clazz.getDeclaredFields();
            for (Field field : fields) {
                FiledId annotation = field.getAnnotation(FiledId.class);
                if (annotation != null) {
                    String name = annotation.name();
                    String value = temp.get(name);
                    field.setAccessible(true);
                    try {
                        field.set(this, value);
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    protected abstract int headerLength();

    public String getHeader() {
        return header;
    }

    /**
     * 返回字符串头部第三位1代表返回OK
     *
     * @return
     */
    public boolean isSuccess() {
        String message = getHintMessage();
        if ("单册没有借出".equals(message)) {
            return true;
        }
        return message != null && message.contains("成功");
    }

    protected abstract String getHintMessage();

}
